/// <reference path="../../../typings/index.d.ts"/>
/// <reference path="../../../typings/htmlimp.d.ts"/>
import { WidgetInterface } from "@interfaces/widgetInterface";
import { ApiPageInterface } from "@interfaces/apiPageInterface";
import { ApiWidgetInterface } from "@interfaces/apiWidgetInterface";

//import * as a from "module";
import "./assets/widget.less";

export default class WidgetSimple implements WidgetInterface {
    pageApi: ApiPageInterface;
    widgetApi: ApiWidgetInterface;

    _option: any = {
        version: "1.0",
        test: { text: "文本测试" },
    };

    timelinePointer: any;

    container: HTMLElement;

    constructor({ timelinePointer }) { this.timelinePointer = timelinePointer }

    public async init(container: HTMLElement) {
        this.container = container;
    }

    public setOption(option: any) {
        this._option = _.cloneDeep(option);
    }

    public getOption() {
        return _.cloneDeep(this._option);
    }

    public setData(data: any) {
        console.log("数据打包上来了");
        console.log(data);
    }

    renderScroller = (timelines = [], pointerPositionLeft?) => {
        const max = 235959
        const $scroller = $(this.container).find('.time-scroller');

        $scroller.find('.time-axis-scroll').remove();
        timelines.map((item, index) => {
            const [start, end] = item.split('_');
            let __start = start.substr(8)
            const __end = end.substr(8)

            if (+__start >= +__end) __start = '000000'
            const width = __end - __start;
            const __width = ~~((width / max) * 10000) / 100
            const left = ~~(__start / max * 10000) / 100

            console.log(start, end, __start, __end, (width)) // ~~(0.3333333 * 10000) / 100
            $scroller.append(
                $('<div class="time-axis-scroll"/>')
                    .css('width', `${__width}%`)
                    .css('left', `${left}%`)
            );

            if (index === 0) {
                $scroller.find('.time-pointer').css('left', pointerPositionLeft || left);
            }
            // $scroller.append($('<div class="time-axis-scroll"/>').css('width', '50px'));
        });
    }

    renderScrollerByDatetime = (timelines = [], pointerPositionLeft?) => {
        const max = 235959
        const $scroller = $(this.container).find('.time-scroller');

        $scroller.find('.time-axis-scroll').remove();
        timelines.map((item, index) => {
            const { start_time, end_time, url } = item;
            const __start = start_time.replace(/:/g, '')
            const __end = end_time.replace(/:/g, '')
            const width = __end - __start;
            const __width = ~~((width / max) * 10000) / 100
            const left = ~~(__start / max * 10000) / 100

            console.log(start_time, end_time, __start, __end, (width)) // ~~(0.3333333 * 10000) / 100
            $scroller.append(
                $('<div class="time-axis-scroll"/>')
                    .attr('url', url.http)
                    .css('width', `${__width}%`)
                    .css('left', `${left}%`)
            );

            if (index === 0) {
                $scroller.find('.time-pointer').css('left', pointerPositionLeft || `${left}%`);
            }
            // $scroller.append($('<div class="time-axis-scroll"/>').css('width', '50px'));
        });
    }

    clearScroller = () => {
        const $scroller = $(this.container).find('.time-scroller');
        $scroller.find('.time-axis-scroll').remove();
        $scroller.find('.time-pointer').css('left', `0%`);
    }

    initScroller = () => {
        const $scroller = $(this.container).find('.time-scroller');

        if ($scroller.length) {
            const $pointer = $('<div class="time-pointer"><div class="time-arrow"></div></div>');
            let { x } = $scroller[0].getBoundingClientRect();
            let width;
            let left;
            this.renderScroller();

            console.log($scroller.children().has($pointer as any))
            if (!$scroller.children().has($pointer as any).length) {
                $scroller.append($pointer);
            }
            $scroller.on('click', '.time-axis-scroll', (event) => {
                console.log(event);
                const $scroll = $(event.target).closest('.time-scroller');
                width = $scroll.width();  // 获取当前组件的宽度
                const left =event.offsetX + event.target.offsetLeft;
                const url = $(event.target).attr('url');

                if (!$scroller.children().has($pointer as any).length) {
                    $scroller.append($pointer);
                }

                $pointer.css('left', left);
                console.log({ left, width });

                this.widgetApi?.emitEvent('timeline:click', { left, width, url });
                this?.timelinePointer?.(url, left, width);
            });

            const mousemove = (event) => {
                left = event.pageX - x;
                // console.log({ left, width });
                if (left > width - 5) {
                    left = width - 5;
                } else {
                    if (left < 0) left = 0;
                }
                $pointer.css('left', left);
            }

            const offMousemove = (event) => {
                event.stopPropagation();
                const $scroller = $(this.container).find('.time-axis-scroll');
                const $scroll = $(this.container).find('.time-scroller');
                const width = $scroll.width();  // 获取当前组件的宽度
                const url = $scroller.attr('url');

                console.log('offMousemove: => ', { left, width });
                this.widgetApi?.emitEvent('timeline:click', { left, width, url });
                this?.timelinePointer?.(url, left, width);
                $(document.body).off('mousemove', mousemove);
            }

            $scroller.on('mousedown', '.time-pointer', (event) => {
                event.stopPropagation();
                const $scroll = $(event.target).closest('.time-scroller').find('.time-axis-scroll');

                if ($scroll.length > 1) {
                    const $item = $scroll.eq($scroll.length - 1);
                    width = $item.width() + $item.offset().left;
                } else {
                    width = $scroll.width();
                }

                ({ x } = $scroller[0].getBoundingClientRect());
                $(document.body).on('mousemove', mousemove);
                $(document.body).on('mouseup', offMousemove);
            });

            $scroller.on('mouseup', '.time-pointer', offMousemove);
        }
    }

    renderTimeline = () => {
        const $timeline = $(this.container).find('.time-timeline')
        const hour = new Array(24).fill(null);

        if ($timeline.length) {
            hour.forEach((_, index) => {
                // const idx = (index < 10) ? `0${index}:00` : `${index}:00`;
                const idx = (index < 10) ? `0${index}` : `${index}`;
                $timeline.append($(`<div class="timeline-hour">${idx}</div>`));
            });
        }
    }

    public render(container?) {
        if (container) this.container = container
        const $container = $(this.container);
        $container.html(`
      <div class="time-axis">
        <div class="time-scroller"></div>
        <div class="time-timeline"></div>
      </div>
    `);

        this.initScroller();
        this.renderTimeline();
    }
    public resize() { }

    public dispose() { }
}
